package org.amj;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.amj.srt.Srt;
import org.amj.srt.SrtEntry;

public class SubtitleCreator1 {
	private static Pattern entryPattern = Pattern.compile("\\s*([0-9]{1,2})\\.([0-9]{1,2})\\s*:\\s*([0-9]{1,2})\\.([0-9]{1,2})\\s*(.*)");

	public static void main(String[] args) {
		//testShift();
		//testShorten();
		makeSubtitles(Data.data1);
		makeSubtitles(Data.data2);
//		makeSubtitles(Data.data3);
		
	}

	private static void makeSubtitles(String data1) {
		Srt srt = new Srt();
		try{
			BufferedReader br = new BufferedReader(new StringReader(data1));
			String strLine;
			while ((strLine = br.readLine()) != null)   {
				if(!strLine.trim().isEmpty()) {
					System.out.println (strLine);
					addEntry(srt, strLine);
				}
			}
		} catch (Exception e){
			System.err.println("Error: " + e.getMessage());
		}


		srt.shortenEnteries(80);

		System.out.println(srt.toSrtText());
	}

	private static void addEntry(Srt srt, String strLine) {

		Matcher m = entryPattern.matcher(strLine);
		if (m.matches()) {
			
			int minuteStart = Integer.parseInt(m.group(1));
			int secondStart = Integer.parseInt(m.group(2));
			int minuteEnd = Integer.parseInt(m.group(3));
			int secondEnd = Integer.parseInt(m.group(4));
			String text = m.group(5);
			
			SrtEntry newEntry = srt.newEntry(0, minuteStart, secondStart, 0, 0, minuteEnd, secondEnd, 0, text);
			//System.out.println(newEntry);
			srt.getEntries().add(newEntry);
		}		
	}

	private static void testShorten() {
		Srt srt = new Srt();

		String string = "In my experience, regular expression can get you pretty far, but it cannot do everything. You could probably produce a regex for splitting words OR a regex for splitting every n characters, but there is no way to combine these two regular expressions in any way other than \"or\". My advice is to split by words and generate a method which selects multiple words based on # of characters provided by the user";
		srt.getEntries().add(srt.newEntry(1,0,0,0,1,4,4,0,string));

		srt.shortenEnteries(50);

		System.out.println(srt.toSrtText());
	}

	private static void testShift() {
		Srt srt = new Srt();

		srt.getEntries().add(srt.newEntry(1,0,0,0,1,0,4,0,"Hola"));
		srt.getEntries().add(srt.newEntry(1,0,5,0,1,0,8,0,"Hi"));
		srt.getEntries().add(srt.newEntry(1,2,40,0,1,55,32,8,"Bye"));

		System.out.println(srt.toSrtText());

		srt.shift(7267);
		System.out.println(srt.toSrtText());

		srt.shift(-7267);
		System.out.println(srt.toSrtText());
	}
}
